package com.sunbim.rsrv.controller.v1;


import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunbim.rsrv.common.exception.RequestException;
import com.sunbim.rsrv.params.common.Ids;
import com.sunbim.rsrv.params.relics.RiskUpdateParams;
import com.sunbim.rsrv.pojo.Relics;
import com.sunbim.rsrv.service.RelicsService;
import com.sunbim.rsrv.vo.relics.RelicsWithRiskVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yuhui
 * @since 2021-12-30
 */
@Api(tags = "文物")
@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/relics")
public class RelicsController {
    @Autowired
    RelicsService relicsService;

    /**
     * 目前查询所有文物、根据用户id查询文物返回的字段都是全部
     * 然而实际前端页面中用于展示的列表并不需要全部字段, 可以修改接口或者添加新接口, 仅仅返回需要的字段, 如文物id、文物编码、文物名称、年代、地址、级别/批次,
     * 前端在进入详情页时 根据文物的id直接查单个数据即可
     */

    @ApiOperation(value = "分页查询所有文物", notes = "1.需要管理员权限<br/>2.若pageSize=0或没有传pageSize则不进行分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页数", dataTypeClass = int.class, required = false, defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "分页size", dataTypeClass = int.class, required = false, defaultValue = "0")
    })
    @SaCheckRole("admin")
    @GetMapping("selectAll")
    // pageHelper
    public PageInfo<Map<String, Object>> selectAll(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "0") int pageSize
    ) {
        if (pageSize != 0) PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> relicsList = relicsService.getAll();
        return PageInfo.of(relicsList);
    }

    @ApiOperation(value = "根据用户id分页查询所有文物", notes = "1.需要管理员权限<br/>2.若pageSize=0或没有传pageSize则不进行分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户id", dataTypeClass = int.class, required = true),
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页数", dataTypeClass = int.class, required = false, defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "分页size", dataTypeClass = int.class, required = false, defaultValue = "0")
    })
    @GetMapping("selectAllByUserId")
    public PageInfo<Relics> selectAllByUserId(
            @RequestParam(value = "user_id") int userId,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "0") int pageSize
    ) {
        if (pageSize != 0) PageHelper.startPage(pageNum, pageSize);
        List<Relics> relicsList = relicsService.getAllByUserId(userId);
        return PageInfo.of(relicsList);
    }

    @ApiOperation(value = "分页查询当前登录用户的所有文物", notes = "1.不需要传递用户id<br/>2.若pageSize=0或没有传pageSize则不进行分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页数", dataTypeClass = int.class, required = false, defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "分页size", dataTypeClass = int.class, required = false, defaultValue = "0")
    })
    @GetMapping("selectAllByLoginUser")
    public PageInfo<Relics> selectAllByLoginUser(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "0") int pageSize
    ) {
        int loginUserId = StpUtil.getLoginIdAsInt();
        if (pageSize != 0) PageHelper.startPage(pageNum, pageSize);
        List<Relics> relicsList = relicsService.getAllByUserId(loginUserId);
        return PageInfo.of(relicsList);
    }

    @ApiOperation(value = "查询一条文物数据", notes = "")
    @ApiImplicitParam(paramType = "query", name = "id", value = "文物id", dataTypeClass = int.class, required = true)
    @GetMapping("select")
    public Relics select(@RequestParam(value = "id") Integer relicsId) {
        // 先获取当前登录用户的权限
        List<String> roleList = StpUtil.getRoleList();
        String role = roleList.get(0);

        // 如果是管理员,则直接根据文物id查询
        if ("admin".equals(role)) {
            return relicsService.selectOne(relicsId);
        }
        // 如果不是管理员,则查询登录用户所拥有的文物
        return relicsService.selectOne(StpUtil.getLoginIdAsInt(), relicsId);
    }

    @ApiOperation(value = "根据用户id和条件分组查询文物数据", notes = "1.需要管理员权限<br/>2.条件为其中的一个:<br/>地区: region<br/>文物类型: type<br/>文物级别: grade")
    @SaCheckRole("admin")
    @GetMapping("select/condition")
    public List<Map<String, Object>> selectByUserIdWithCondition(
            @RequestParam(value = "user_id") Integer userId,
            @RequestParam(value = "condition") String condition
    ) {
        return relicsService.selectByUserIdWithCondition(userId, condition);
    }

    @ApiOperation(value = "根据条件分组查询当前登录用户的文物数据", notes = "条件为其中的一个:<br/>地区: region<br/>文物类型: type<br/>文物级别: grade")
    @GetMapping("select/condition/loginUser")
    public List<Map<String, Object>> selectByLoginUserWithCondition(@RequestParam(value = "condition") String condition) {
        int userId = StpUtil.getLoginIdAsInt();
        return relicsService.selectByUserIdWithCondition(userId, condition);
    }

    @ApiOperation(value = "根据用户id查询带有风险等级的文物列表", notes = "需要管理员权限")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户id", dataTypeClass = int.class, required = true),
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页数", dataTypeClass = int.class, required = false, defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "分页size", dataTypeClass = int.class, required = false, defaultValue = "0")
    })
    @SaCheckRole("admin")
    @GetMapping("/select/dangerList")
    public PageInfo<Map<String, Object>> selectByIdWithDanger(
            @RequestParam(value = "user_id") Integer userId,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "0") int pageSize
    ) {
        if (pageSize != 0) PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> list = relicsService.getAllByUserIdWithDanger(userId);
        return PageInfo.of(list);
    }

    @ApiOperation(value = "根据当前登录用户查询带有风险等级的文物列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页数", dataTypeClass = int.class, required = false, defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "分页size", dataTypeClass = int.class, required = false, defaultValue = "0")
    })
    @GetMapping("/select/dangerListByLoginUser")
    public PageInfo<Map<String, Object>> selectByLoginUserWithDanger(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "0") int pageSize
    ) {
        if (pageSize != 0) PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> list = relicsService.getAllByUserIdWithDanger(StpUtil.getLoginIdAsInt());
        return PageInfo.of(list);
    }


    @ApiOperation(value = "查询一条文物的风险数据", notes = "非管理员查询登录用户的风险数据")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "user_id", value = "用户id", dataTypeClass = int.class, required = false),
            @ApiImplicitParam(paramType = "query", name = "relics_id", value = "文物id", dataTypeClass = int.class, required = true)
    })
    @GetMapping("select/risk")
    public RelicsWithRiskVo selectRisk(
            @RequestParam(value = "user_id", required = false) Integer userId,
            @RequestParam(value = "relics_id") Integer relicsId
    ) {
        // 先获取当前登录用户的权限
        List<String> roleList = StpUtil.getRoleList();
        String role = roleList.get(0);

        // 如果是管理员,则直接根据文物id查询
        if ("admin".equals(role) && ObjectUtil.isNotNull(userId)) {
            return relicsService.selectRiskOne(userId, relicsId);
        }
        // 如果不是管理员,则查询登录用户所拥有的文物
        return relicsService.selectRiskOne(StpUtil.getLoginIdAsInt(), relicsId);
    }

    @ApiOperation(value = "更新文物风险信息", notes = "需要管理员权限")
    @SaCheckRole("admin")
    @PostMapping("update/risk")
    public String updateRisk(@RequestBody RiskUpdateParams params) {
        relicsService.updateRisk(params);
        return "更新成功";
    }

    @ApiOperation(value = "插入一条文物数据", notes = "")
    @SaCheckRole("admin")
    @PostMapping("insert")
    public String insertOne(

            @NotNull(message = "用户id不能为空")
            @ApiParam(value = "用户id", required = true)
            @RequestParam(value = "user_id", required = true) Integer userId,

            @ApiParam(value = "文物地区", required = false)
            @RequestParam(value = "region", required = false) String relicsRegion,

            @ApiParam(value = "文物类别", required = false)
            @RequestParam(value = "type", required = false) String relicsType,

            @NotBlank(message = "文物名称不能为空")
            @ApiParam(value = "文物名称", required = true)
            @RequestParam(value = "name", required = true) String relicsName,

            @ApiParam(value = "文物年代", required = false)
            @RequestParam(value = "age", required = false) String relicsAge,

            @ApiParam(value = "文物代码", required = false)
            @RequestParam(value = "code", required = false) String relicsCode,

            @ApiParam(value = "文物保护面积", required = false)
            @RequestParam(value = "area", required = false) Double relicsArea,

            @ApiParam(value = "文物发布时间", required = false)
            @RequestParam(value = "pubtime", required = false) String pubtime,

            @ApiParam(value = "文物发布代码", required = false)
            @RequestParam(value = "pubcode", required = false) String relicsPubcode,

            @ApiParam(value = "文物所有权", required = false)
            @RequestParam(value = "ownership", required = false) String relicsOwnership,
            @ApiParam(value = "文物使用人", required = false)
            @RequestParam(value = "owner", required = false) String relicsOwner,

            @ApiParam(value = "文物管理机构", required = false)
            @RequestParam(value = "manager", required = false) String relicsManager,

            @ApiParam(value = "文物使用方式", required = false)
            @RequestParam(value = "way", required = false) String relicsWay,

            @ApiParam(value = "文物级别", required = false)
            @RequestParam(value = "grade", required = false) String relicsGrade,

            @ApiParam(value = "文物级别/批次", required = false)
            @RequestParam(value = "grand_batch", required = false) String relicsGrandBatch,

            @ApiParam(value = "文物简介", required = false)
            @RequestParam(value = "abstracts", required = false) String relicsAbstracts,

            @ApiParam(value = "文物概况", required = false)
            @RequestParam(value = "overview", required = false) String relicsOverview,

            @ApiParam(value = "文物坐标", required = false)
            @RequestParam(value = "geo", required = false) String relicsGeo,

            @ApiParam(value = "文物详细地址", required = false)
            @RequestParam(value = "address", required = false) String relicsAddress,

            @ApiParam(value = "文物封面图片", required = false)
            @RequestParam(value = "file", required = false) MultipartFile file
    ) {
        LocalDateTime relicsPubtime = LocalDateTimeUtil.parse(pubtime, DatePattern.NORM_DATETIME_PATTERN);
        Relics relics = new Relics();
        relics.setUserId(userId);
        relics.setRelicsRegion(relicsRegion);
        relics.setRelicsType(relicsType);
        relics.setRelicsName(relicsName);
        relics.setRelicsAge(relicsAge);
        relics.setRelicsCode(relicsCode);
        relics.setRelicsArea(relicsArea);
        relics.setRelicsPubtime(relicsPubtime);
        relics.setRelicsPubcode(relicsPubcode);
        relics.setRelicsOwnership(relicsOwnership);
        relics.setRelicsOwner(relicsOwner);
        relics.setRelicsManager(relicsManager);
        relics.setRelicsWay(relicsWay);
        relics.setRelicsGrade(relicsGrade);
        relics.setRelicsGrandBatch(relicsGrandBatch);
        relics.setRelicsAbstracts(relicsAbstracts);
        relics.setRelicsOverview(relicsOverview);
        relics.setRelicsGeo(relicsGeo);
        relics.setRelicsAddress(relicsAddress);

        relicsService.insertOne(relics, file);
        return "添加成功";
    }

    @ApiOperation(value = "更新一条文物数据", notes = "")
    @ApiImplicitParam(paramType = "path", name = "id", value = "文物的id", dataTypeClass = int.class, required = true)
    @SaCheckRole("admin")
    @PostMapping("update")
    public String update(
            @Valid @RequestBody Relics relics
    ) {
        relicsService.updateByRelicsId(relics);
        return "更新成功";
    }

    @ApiOperation(value = "删除一条文物数据", notes = "1.需要管理员权限<br/>2.没有设置逻辑删除")
    @ApiImplicitParam(paramType = "path", name = "id", value = "文物的id", dataTypeClass = int.class, required = true)
    @SaCheckRole("admin")
    @GetMapping("delete/{id}")
    public String delete(@PathVariable("id") int id) {
        relicsService.deleteRelics(id);
        return "删除成功";
    }

    @Transactional
    @ApiOperation(value = "批量删除文物数据", notes = "1.需要管理员权限<br/>2.没有设置逻辑删除")
    @SaCheckRole("admin")
    @PostMapping("delete")
    public String delete(@RequestBody Ids params) {
        if (ObjectUtil.isNull(params.getIds()) || params.getIds().size() == 0)
            throw new RequestException("删除的id列表不能为空");
        relicsService.deleteRelics(params.getIds());
        return "删除成功";
    }

    //2022-2-23 yuhui 根据用户id,文物名称模糊查找)
    @ApiOperation(value = "根据文物名称模糊查询文物列表", notes = "非管理员查询登录用户的文物列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "user_id", value = "用户id", dataTypeClass = int.class, required = false),
            @ApiImplicitParam(paramType = "query", name = "keyword", value = "文物的名称关键字", dataTypeClass = String.class, required = true)
    })
    @GetMapping("searchByRelicsName")
    public List<Map<String, Object>> searchByRelicsName(
            @RequestParam(value = "user_id", required = false) Integer userId
    //      @RequestParam(value = "keyword") String keyword
    ) {
        // 先获取当前登录用户的权限
        List<String> roleList = StpUtil.getRoleList();
        String role = roleList.get(0);

        // 如果是管理员,则直接根据文物名称关键字查询
        if ("admin".equals(role) && ObjectUtil.isNotNull(userId)) {
            return relicsService.searchByRelicsName(userId);
        }
        // 如果不是管理员,则根据文物名称关键字，查询登录用户所拥有的文物
        return relicsService.searchByRelicsName(StpUtil.getLoginIdAsInt());
    }

    // 2022-2-27 yuhui 根据用户id返回文物列表
    @ApiOperation(value = "根据用户id分页查询所有文物", notes = "1.需要管理员权限<br/>2.若pageSize=0或没有传pageSize则不进行分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "user_id", value = "用户id", dataTypeClass = int.class, required = false),
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页数", dataTypeClass = int.class, required = false, defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "分页size", dataTypeClass = int.class, required = false, defaultValue = "0")
    })

    @GetMapping("selectAllRelicsByUserId")
    public PageInfo<Relics> selectAllRelicsByUserId(
            @RequestParam(value = "user_id", required = false) Integer userId,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "0") int pageSize
    ) {
        if (pageSize != 0) PageHelper.startPage(pageNum, pageSize);
        // 先获取当前登录用户的权限
        List<String> roleList = StpUtil.getRoleList();
        String role = roleList.get(0);

        // 如果是管理员,则直接根据文物名称关键字查询
        if ("admin".equals(role) && ObjectUtil.isNotNull(userId)) {
            List<Relics> relicsList = relicsService.getAllByUserId(userId);
            return PageInfo.of(relicsList);
        }else{
            List<Relics> relicsList = relicsService.getAllByUserId(StpUtil.getLoginIdAsInt());
            return PageInfo.of(relicsList);
        }
    }
}

